package org.mzy.system.controller;

import org.mzy.basic.anno.PreAuthorize;
import org.mzy.system.service.IMenuService;
import org.mzy.system.domain.Menu;
import org.mzy.system.query.MenuQuery;
import org.mzy.basic.util.AjaxResult;
import org.mzy.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    public IMenuService menuService;


    /**
     * 保存和修改公用的
     *
     * @param menu 传递的实体
     * @return Result转换结果
     */
    @PutMapping
    @PreAuthorize(name = "新增/修改菜单", sn = "menu:addOrUpdate")
    public AjaxResult addOrUpdate(@RequestBody Menu menu) {
        try {
            if (menu.getId() != null)
                menuService.update(menu);
            else
                menuService.add(menu);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    @PreAuthorize(name = "删除菜单", sn = "menu:delete")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            menuService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    @PreAuthorize(name = "根据id获取菜单", sn = "menu:get")
    public Menu get(@PathVariable("id") Long id) {
        return menuService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    @PreAuthorize(name = "查询全部菜单", sn = "menu:list")
    public List<Menu> list() {

        return menuService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    @PreAuthorize(name = "分页查询菜单", sn = "menu:json")
    public PageList<Menu> json(@RequestBody MenuQuery query) {
        return menuService.queryByPage(query);
    }

    @GetMapping("/first")
    @PreAuthorize(name = "这个是菜单树？", sn = "menu:first")
    public List<Menu> first() {
        return menuService.first();
    }

    // 批量删除
    @PatchMapping
    @PreAuthorize(name = "批量删除菜单", sn = "menu:batchDel")
    public AjaxResult batchDel(@RequestBody List<Long> ids) {
        menuService.batchDel(ids);
        return AjaxResult.me().success();
    }

    // 树
    @GetMapping("tree")
    @PreAuthorize(name = "菜单树", sn = "menu:tree")
    public List<Menu> tree() {
        return menuService.tree();
    }
}
